<?php
/**
 * Created by PhpStorm.
 * User: Liu
 * Date: 2023/2/27
 * Time: 11:47
 */

namespace app\admin\controller;

use app\admin\common\Base;
use app\admin\model\CategoryProduct as CategoryModel;

class CategoryProduct extends Base {
    public function index(){
        if (is_post()){
            $list = db('category_product')->where('is_del',0)->order('sort','asc')->select();
            if (!empty($list)){
                //open为true，列表中有子级，默认展开，若无需展开，将该段代码注释
                foreach ($list as $k => $v){
                    $list[$k]['open'] = true;
                }
            }
            return json(['code' => 0,'data'=>$list]);
        }

        return $this->fetch('category/product');
    }

    public function add(){
        $model = new CategoryModel();
        if (is_post()){
            $data = input('post.');

            $result = $model->add($data);

            return json(['code'=>$result['code'],'msg'=>$result['msg']]);
        }

        $category = $model->getAll();
        $this->assign('category',json_encode($category['related']));

        $tree_category = $this->getTree($category['all']);
        $this->assign('tree_list',$tree_category);

        return $this->fetch('category/add_product');
    }

    public function edit($id){
        $model = new CategoryModel();
        if (is_post()){
            $data = input('post.');

            $result = $model->edit($id,$data);
            return json(['code'=>$result['code'],'msg'=>$result['msg']]);
        }

        $category = $model->getAll();
        $this->assign('category',json_encode($category['related']));

        $tree_category = $this->getTree($category['all']);
        $this->assign('tree_list',$tree_category);

        $info = db('category_product')
            ->where('id',$id)
            ->find();

        $this->assign('info',$info);
        return $this->fetch('category/edit_product');
    }

    public function del($id){
        if (is_post()){
            if ($this->delRecord('category_product',$id,'删除产品分类：')){
                return json(['code' => 'suc','msg' => config('msg.del_suc')]);
            }
            return json(['code' => 'err','msg' => config('msg.err_msg')]);
        }
    }
}